

local ustring = commonlib.inherit(nil, commonlib.gettable("commonlib.ustring"));

local utf8_offset = utf8.offset;
local utf8_len = utf8.len;

function utf8_sub(s, i, j)
    local sl = utf8_len(s);
    i = i or 1;
    j = (not j or j > sl) and sl or j;

    if (i > sl or j < i) then return "" end

    local ui = utf8_offset(s, i);
    local uj = utf8_offset(s, j + 1);
    return string.sub(s, ui, uj - 1);
end

function ustring:ctor()
    self.m_text = "";
end

function ustring:init(text)
    self.m_text = text or "";
    return self;
end

function ustring:tostring()
    return self.m_text;
end

function ustring:len()
    return utf8_len(self.m_text);
end

function ustring:sub(i, j)
    return ustring:new(utf8_sub(self.m_text, i, j));
end

function ustring:insert(pos, text)
    text = tostring(text);
    self.m_text = utf8_sub(self.m_text, 1, pos - 1) .. text .. utf8_sub(self.m_text, pos);
end

function ustring:remove(pos, size)
    self.m_text = utf8_sub(self.m_text, 1, pos - 1)  .. utf8_sub(self.m_text, pos + size);
end

setmetatable(ustring, {
    __call = function(us, text)
        return us:new():init(text);
    end,

    __tostring = function(us)
        return us:tostring() or "";
    end,
});

commonlib.ustring = ustring;
commonlib.utf8_len = utf8_len;
commonlib.utf8_sub = utf8_sub;

function commonlib.split(str, delimiter)
	local list = {};
    delimiter = delimiter or "%s";

	if(not str or str == "") then return list end

    local s = "([^"..delimiter.."]+)";
	for substr in string.gmatch(str, s) do
		table.insert(list, substr);
	end
	return list;
end

function commonlib.trim(str, ch)
	ch = ch or "%s";
    str = string.gsub(str, "^" .. ch .. "*", "");
    str = string.gsub(str, ch .. "*$", "");
    return str;
end

return ustring;